<template>
  <el-config-provider :locale="zhCn">
    <div class="ai-train-container">
      <!-- 筛选条件区域 -->
      <filter-form v-model="filterForm" :form-items="formItems" @search="handleSearch" @reset="resetFilter" @update:modelValue="handleFilterChange" />

      <!-- 选项卡区域 -->
      <el-tabs v-model="activeTab" type="card" class="ai-train-tabs" @tab-click="handleTabClick">
        <!-- AI模型 -->
        <el-tab-pane label="AI模型" name="aiModel">
          <div class="table-section">
            <div class="operation-section">
              <el-button type="success" @click="handleAddModel">新增模型</el-button>
            </div>
            <el-table :data="modelList" border style="width: 100%" v-loading="loading" class="custom-table">
              <el-table-column type="index" label="序号" width="60" />
              <el-table-column prop="modelName" label="所属行业" min-width="150" />
              <el-table-column prop="aiRoleSetting" label="AI角色设定" min-width="200">
                <template #default="{ row }">
                  <div class="content-text">{{ row.aiRoleSetting }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="businessBackground" label="企业背景" min-width="200">
                <template #default="{ row }">
                  <div class="content-text">{{ row.businessBackground }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="dialogueCase" label="对话案例" min-width="200">
                <template #default="{ row }">
                  <div class="content-text">{{ row.dialogueCase }}</div>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200" fixed="right">
                <template #default="{ row }">
                  <el-button type="primary" link @click="handleEditModel(row)">编辑</el-button>
                  <el-button type="danger" link @click="handleDeleteModel(row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 话术训练 -->
        <el-tab-pane label="话术训练" name="languageSkill">
          <div class="language-skill-layout">
            <!-- 左侧组织机构树 -->
            <div class="organization-tree-section">
              <div class="tree-header">
                <div class="header-content">
                  <h4>分类架构</h4>
                  <el-button type="primary" size="small" @click="handleAddSecondLevelOrganization()"> 新增 </el-button>
                </div>
              </div>
              <div class="tree-container">
                <div v-if="organizationTreeData.length === 0" class="empty-state">
                  <div class="empty-icon">📋</div>
                  <div class="empty-text">暂无分类架构</div>
                  <div class="empty-desc">请联系管理员添加分类架构</div>
                </div>
                <el-tree
                  v-else
                  ref="organizationTreeRef"
                  :data="organizationTreeData"
                  :props="treeProps"
                  node-key="id"
                  :default-expanded-keys="defaultExpandedKeys"
                  :expand-on-click-node="false"
                  :highlight-current="true"
                  @node-click="handleTreeNodeClick"
                  @node-contextmenu="handleTreeNodeRightClick"
                  class="organization-tree"
                >
                  <template #default="{ node, data }">
                    <div class="tree-node" @contextmenu.prevent="handleTreeNodeRightClick($event, data, node)" :data-level="data.level">
                      <span class="node-label">{{ node.label }}</span>
                      <div class="node-actions" v-if="data.level > 0">
                        <el-dropdown trigger="click" @command="(command) => handleNodeAction(command, data, node)">
                          <el-button type="text" size="small" class="action-btn">
                            <el-icon><MoreFilled /></el-icon>
                          </el-button>
                          <template #dropdown>
                            <el-dropdown-menu>
                              <el-dropdown-item command="add">新增子分类</el-dropdown-item>
                              <el-dropdown-item command="edit">编辑</el-dropdown-item>
                              <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
                            </el-dropdown-menu>
                          </template>
                        </el-dropdown>
                      </div>
                      <div class="node-actions" v-else>
                        <el-dropdown trigger="click" @command="(command) => handleNodeAction(command, data, node)">
                          <el-button type="text" size="small" class="action-btn">
                            <el-icon><MoreFilled /></el-icon>
                          </el-button>
                          <template #dropdown>
                            <el-dropdown-menu>
                              <el-dropdown-item command="add">新增子分类</el-dropdown-item>
                            </el-dropdown-menu>
                          </template>
                        </el-dropdown>
                      </div>
                    </div>
                  </template>
                </el-tree>
              </div>
            </div>

            <!-- 右侧话术列表 -->
            <div class="table-section">
              <div class="operation-section">
                <el-button :disabled="selectedOrganizationId ? false : true" type="success" @click="handleAddScript">新增</el-button>
                <el-button :disabled="selectedOrganizationId ? false : true" type="info" @click="handleUploadScript" :loading="importScriptLoading"
                  >导入</el-button
                >
                <el-button :disabled="selectedOrganizationId ? false : true" type="primary" @click="handleExportScript" :loading="exportScriptLoading"
                  >导出</el-button
                >
                <el-button :disabled="selectedOrganizationId ? false : true" type="warning" @click="handleDownloadTemplate">下载模板</el-button>
              </div>
              <el-table :data="scriptList" border style="width: 100%" v-loading="loading" class="custom-table">
                <el-table-column type="index" label="序号" width="60" />
                <el-table-column prop="departmentName" label="所属分类" min-width="120">
                  <template #default="{ row }">
                    <div class="content-text">{{ row.departmentName || '-' }}</div>
                  </template>
                </el-table-column>
                <el-table-column prop="umWechatAiModel.modelName" label="所属模型" min-width="120">
                  <template #default="{ row }">
                    <div class="content-text">{{ row.umWechatAiModel?.modelName || '-' }}</div>
                  </template>
                </el-table-column>
                <el-table-column prop="issue" label="问题" min-width="200">
                  <template #default="{ row }">
                    <div class="content-text">{{ row.issue }}</div>
                  </template>
                </el-table-column>
                <el-table-column prop="answer" label="回答" min-width="200">
                  <template #default="{ row }">
                    <div class="content-text">{{ row.answer }}</div>
                  </template>
                </el-table-column>
                <el-table-column prop="status" label="状态标签" width="100">
                  <template #default="{ row }">
                    <el-tag :type="row.status == '1' ? 'success' : row.status == '2' ? 'danger' : 'warning'" size="small">
                      {{ row.status == '1' ? '启用' : row.status == '2' ? '禁用' : '审批中' }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="{ row }">
                    <el-tooltip :content="row.status == '0' ? '审批中，无法操作' : row.type == '1' ? '点击禁用' : '点击启用'" placement="top" effect="dark">
                      <el-switch v-model="row.type" :active-value="'1'" :inactive-value="'2'" :disabled="row.status == '0'" @change="handleStatusChange(row)" />
                    </el-tooltip>
                  </template>
                </el-table-column>
                <el-table-column prop="createByStr" label="创建人" width="120" />
                <el-table-column prop="createTime" label="创建时间" width="180" />
                <el-table-column label="操作" width="150" fixed="right">
                  <template #default="{ row }">
                    <el-button v-if="row.status != '0'" type="primary" link @click="handleEditScript(row)">编辑</el-button>
                    <el-button type="danger" link @click="handleDeleteScript(row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-tab-pane>

        <!-- 文件训练 -->
        <el-tab-pane label="文件训练" name="file">
          <div class="table-section">
            <div class="operation-section">
              <el-button type="success" @click="handleUploadFile" :loading="uploadFileLoading">上传文件</el-button>
            </div>
            <el-table :data="fileList" border style="width: 100%" v-loading="loading" class="custom-table">
              <el-table-column type="index" label="序号" width="60" />
              <el-table-column prop="fileName" label="文件名" min-width="200" />
              <el-table-column prop="fileSize" label="文件大小" width="120" />
              <el-table-column prop="createByStr" label="创建人" width="120" />
              <el-table-column prop="createTime" label="创建时间" width="180" />
              <el-table-column label="操作" width="100" fixed="right">
                <template #default="{ row }">
                  <el-button type="danger" link @click="handleDeleteFile(row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>

      <!-- 分页 -->
      <pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total" @pagination="handlePagination" />

      <!-- 添加/编辑模型对话框 -->
      <el-dialog v-model="modelDialogVisible" :title="dialogType === 'add' ? '新增模型' : '编辑模型'" width="800px" destroy-on-close class="model-dialog">
        <el-form ref="modelFormRef" :model="modelForm" :rules="modelFormRules" label-width="120px" class="model-form">
          <el-form-item label="所属行业" prop="modelName" required>
            <div class="industry-input">
              <el-input v-model="modelForm.modelName" :disabled="templateDisabled" placeholder="请输入所属行业" />
              <el-button type="primary" link @click="handleGenerateTemplate" :loading="generatingTemplate" :disabled="generatingTemplate">
                {{ generatingTemplate ? '生成中...' : '一键生成模板' }}
              </el-button>
            </div>
          </el-form-item>
          <el-form-item prop="aiRoleSetting" required>
            <template #label>
              <div class="form-label">
                <span>AI角色设定</span>
                <el-tooltip content="设定AI在对话中的角色定位和专业领域" placement="top">
                  <el-icon><QuestionFilled /></el-icon>
                </el-tooltip>
              </div>
            </template>
            <el-input
              v-model="modelForm.aiRoleSetting"
              type="textarea"
              :rows="3"
              placeholder="请输入AI角色设定，例如：作为行业专家，我将为客户提供专业的咨询和建议"
              :disabled="templateDisabled"
              maxlength="2000"
              show-word-limit
            />
          </el-form-item>
          <el-form-item prop="businessBackground" required>
            <template #label>
              <div class="form-label">
                <span>企业背景</span>
                <el-tooltip content="描述企业的基本情况、优势和特色" placement="top">
                  <el-icon><QuestionFilled /></el-icon>
                </el-tooltip>
              </div>
            </template>
            <el-input
              v-model="modelForm.businessBackground"
              type="textarea"
              :rows="6"
              placeholder="请输入企业背景，例如：我们是一家专注于该领域的企业，拥有丰富的行业经验和专业的服务团队"
              :disabled="templateDisabled"
              maxlength="2000"
              show-word-limit
            />
          </el-form-item>
          <el-form-item prop="dialogueCase" required>
            <template #label>
              <div class="form-label">
                <span>对话案例</span>
                <el-tooltip content="提供示例对话，展示AI如何回答客户问题" placement="top">
                  <el-icon><QuestionFilled /></el-icon>
                </el-tooltip>
              </div>
            </template>
            <el-input
              v-model="modelForm.dialogueCase"
              type="textarea"
              :rows="6"
              placeholder="请输入对话案例，包含问题和回答，例如：客户：我想了解一下行业的最新发展趋势。AI：作为行业专家，我可以为您分析当前行业的发展趋势..."
              :disabled="templateDisabled"
              maxlength="2000"
              show-word-limit
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="modelDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleModelSubmit">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 添加/编辑话术对话框 -->
      <el-dialog v-model="scriptDialogVisible" :title="scriptForm.id ? '编辑话术' : '新增话术'" width="800px" destroy-on-close class="script-dialog">
        <el-form :model="scriptForm" label-width="100px" class="script-form">
          <el-form-item label="所属分类">
            <span v-if="scriptForm.id && scriptForm.departmentName" class="selected-org">{{ scriptForm.departmentName }}</span>
            <span v-else-if="selectedOrganizationId" class="selected-org">{{ getSelectedOrganizationName() }}</span>
            <span v-else class="text-muted">-</span>
          </el-form-item>
          <el-form-item label="选择模型" required>
            <el-select v-model="scriptForm.modelId" placeholder="请选择模型" class="model-select">
              <el-option v-for="item in modelOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="问题" required>
            <el-input v-model="scriptForm.question" type="textarea" :rows="3" placeholder="请输入问题" maxlength="2000" show-word-limit />
          </el-form-item>
          <el-form-item label="回答" required>
            <el-input v-model="scriptForm.answer" type="textarea" :rows="6" placeholder="请输入回答" maxlength="2000" show-word-limit />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="scriptDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleScriptSubmit">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 导入话术对话框 -->
      <el-dialog v-model="importScriptDialogVisible" title="导入数据" width="700px" destroy-on-close class="import-script-dialog">
        <div class="import-container">
          <!-- 步骤指引 -->
          <div class="import-steps">
            <div class="step-item">
              <div class="step-number">1</div>
              <div class="step-content">
                <h4>下载模板</h4>
                <p>下载标准导入模板</p>
              </div>
            </div>
            <div class="step-arrow">→</div>
            <div class="step-item">
              <div class="step-number">2</div>
              <div class="step-content">
                <h4>填写数据</h4>
                <p>按模板格式填写话术信息</p>
              </div>
            </div>
            <div class="step-arrow">→</div>
            <div class="step-item">
              <div class="step-number">3</div>
              <div class="step-content">
                <h4>上传文件</h4>
                <p>上传填写好的Excel文件</p>
              </div>
            </div>
          </div>

          <!-- 配置信息 -->
          <div class="config-section">
            <div class="section-header">
              <el-icon class="header-icon"><Setting /></el-icon>
              <span>配置信息</span>
            </div>
            <div class="config-card">
              <el-form :model="importScriptForm" label-width="100px" class="config-form">
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="所属分类">
                      <div class="category-display">
                        <el-icon class="category-icon"><FolderOpened /></el-icon>
                        <span v-if="selectedOrganizationId" class="selected-org">{{ getSelectedOrganizationName() }}</span>
                        <span v-else class="text-muted">未选择分类</span>
                      </div>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="选择模型" required>
                      <el-select v-model="importScriptForm.modelId" placeholder="请选择AI模型" class="model-select">
                        <el-option v-for="item in modelOptions" :key="item.value" :label="item.label" :value="item.value" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
          </div>

          <!-- 模板下载区域 -->
          <div class="template-section">
            <div class="section-header">
              <el-icon class="header-icon"><Download /></el-icon>
              <span>模板下载</span>
            </div>
            <div class="template-card">
              <div class="template-info">
                <el-icon class="file-icon"><Document /></el-icon>
                <div class="file-details">
                  <h5>话术训练导入模板.xlsx</h5>
                  <p>包含问题、答案等必填字段和格式说明</p>
                </div>
              </div>
              <el-button type="primary" @click="handleDownloadTemplate" class="download-btn"> 下载模板 </el-button>
            </div>
          </div>

          <!-- 文件上传区域 -->
          <div class="upload-section">
            <div class="section-header">
              <el-icon class="header-icon"><UploadFilled /></el-icon>
              <span>文件上传</span>
            </div>
            <el-upload
              ref="uploadRef"
              :auto-upload="false"
              :on-change="handleFileChange"
              :file-list="uploadFileList"
              accept=".xlsx,.xls"
              :limit="1"
              drag
              class="upload-area"
            >
              <div class="upload-content">
                <el-icon class="upload-icon"><UploadFilled /></el-icon>
                <div class="upload-text">
                  <p class="main-text">点击或拖拽文件到此区域上传</p>
                  <p class="sub-text">支持 .xlsx、.xls 格式文件，文件大小不超过 100MB</p>
                </div>
              </div>
            </el-upload>
          </div>
        </div>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="importScriptDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleImportScriptSubmit" :loading="importScriptLoading">
              {{ importScriptLoading ? '导入中...' : '确定导入' }}
            </el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 分类架构对话框 -->
      <el-dialog
        v-model="organizationDialogVisible"
        :title="organizationDialogType === 'add' ? '新增分类' : '编辑分类'"
        width="500px"
        destroy-on-close
        class="organization-dialog"
      >
        <el-form :model="organizationForm" label-width="100px" class="organization-form">
          <el-form-item label="分类名称" required>
            <el-input v-model="organizationForm.departmentName" placeholder="请输入分类名称" />
          </el-form-item>
          <el-form-item label="上级分类">
            <span v-if="organizationForm.parentId">{{ getParentDepartmentName(organizationForm.parentId) }}</span>
            <span v-else class="text-muted">顶级分类</span>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="organizationDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleOrganizationSubmit">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </el-config-provider>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Upload, Download, QuestionFilled, MoreFilled, Setting, FolderOpened, Document, UploadFilled } from '@element-plus/icons-vue';
import { useUserStore } from '@/store/modules/user';
import FilterForm from '@/components/FilterForm/index.vue';
import Pagination from '@/components/Pagination/index.vue';
import type { FormItem } from '@/components/FilterForm/index.vue';
import {
  getModelList,
  addAIModel,
  updateAIModel,
  deleteAIModel,
  uploadLanguageSkills,
  getAIModelList,
  addLanguageSkill,
  updateLanguageSkill,
  updateLanguageSkillStatus,
  deleteLanguageSkill,
  exportLanguageSkills,
  getAiTemplate,
  getFileList,
  uploadFile,
  deleteFile,
  getOrganizationTree,
  addOrganization,
  updateOrganization,
  deleteOrganization
} from '@/api/privateModel/aiTrain';
import type { AIModel, LanguageSkill, FileInfo, Organization } from '@/api/privateModel/aiTrain';
import zhCn from 'element-plus/es/locale/lang/zh-cn';

// 获取userStore
const userStore = useUserStore();

// 选项卡相关
const activeTab = ref('languageSkill');

// 筛选表单
const filterForm = reactive({
  modelName: '',
  issue: '',
  answer: '',
  fileName: '',
  status: ''
});

// 筛选项配置
const formItems = computed<FormItem[]>(() => {
  if (activeTab.value === 'aiModel') {
    return [
      {
        type: 'input',
        label: '模型名称',
        prop: 'modelName',
        placeholder: '请输入模型名称'
      }
    ];
  }
  if (activeTab.value === 'languageSkill') {
    return [
      {
        type: 'input',
        label: '问题',
        prop: 'issue',
        placeholder: '请输入问题'
      },
      {
        type: 'input',
        label: '回答',
        prop: 'answer',
        placeholder: '请输入回答'
      },
      {
        type: 'select',
        label: '状态',
        prop: 'status',
        placeholder: '请选择状态',
        options: [
          { label: '全部', value: '' },
          { label: '审批中', value: '0' },
          { label: '启用', value: '1' },
          { label: '禁用', value: '2' }
        ]
      }
    ];
  }
  if (activeTab.value === 'file') {
    return [
      {
        type: 'input',
        label: '文件名',
        prop: 'fileName',
        placeholder: '请输入文件名'
      }
    ];
  }
  return [];
});

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const loading = ref(false);
const importScriptLoading = ref(false);
const exportScriptLoading = ref(false);
const uploadFileLoading = ref(false);

// 列表数据
const modelList = ref<AIModel[]>([]);
const scriptList = ref<LanguageSkill[]>([]);
const fileList = ref<FileInfo[]>([]);
const uploadFileList = ref<any[]>([]);

// 模型选项
const modelOptions = ref<{ value: string; label: string }[]>([]);

// 组织机构树相关
const organizationTreeRef = ref();
const organizationTreeData = ref<Organization[]>([]);
const selectedOrganizationId = ref<number | null>(null);
const defaultExpandedKeys = ref<number[]>([]);

// 树组件配置
const treeProps = {
  children: 'children',
  label: 'departmentName'
};

// 对话框控制
const modelDialogVisible = ref(false);
const scriptDialogVisible = ref(false);
const importScriptDialogVisible = ref(false);
const dialogType = ref('add');
const modelFormRef = ref();
const uploadRef = ref();
const modelForm = reactive<Partial<AIModel>>({
  modelName: '',
  aiRoleSetting: '',
  businessBackground: '',
  dialogueCase: ''
});
const generatingTemplate = ref(false);
const templateDisabled = ref(false);

// 话术表单
const scriptForm = reactive({
  id: '',
  modelId: '',
  question: '',
  answer: '',
  vectorId: '',
  departmentName: ''
});

// 导入话术表单
const importScriptForm = reactive({
  modelId: '',
  file: null as File | null
});

// 组织机构表单
const organizationForm = reactive({
  id: null as number | null,
  departmentName: '',
  parentId: null as number | null,
  level: 0,
  accountType: ''
});

// 组织机构对话框控制
const organizationDialogVisible = ref(false);
const organizationDialogType = ref('add'); // 'add' | 'edit'

// 表单验证规则
const modelFormRules = {
  modelName: [
    { required: true, message: '请输入所属行业', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  aiRoleSetting: [
    { required: true, message: '请输入AI角色设定', trigger: 'blur' },
    { max: 2000, message: '最多输入 2000 个字符', trigger: 'blur' }
  ],
  businessBackground: [
    { required: true, message: '请输入企业背景', trigger: 'blur' },
    { max: 2000, message: '最多输入 2000 个字符', trigger: 'blur' }
  ],
  dialogueCase: [
    { required: true, message: '请输入对话案例', trigger: 'blur' },
    { max: 2000, message: '最多输入 2000 个字符', trigger: 'blur' }
  ]
};

// 获取模型选项
const getModelOptions = async () => {
  try {
    const { data } = await getModelList({ current: 1, size: 100 });
    modelOptions.value = data.records.map((item) => ({
      value: item.id.toString(),
      label: item.modelName
    }));
  } catch (error) {
    console.error('获取模型列表失败:', error);
  }
};

// 获取组织机构树
const getOrganizationTreeData = async () => {
  try {
    const { data } = await getOrganizationTree({
      accountType: userStore.tenantId,
      isDelete: '0'
    });
    organizationTreeData.value = data;

    // 计算默认展开的节点（只展开到二级）
    const expandedKeys: number[] = [];
    const collectExpandedKeys = (nodes: Organization[], level: number = 0) => {
      nodes.forEach((node) => {
        if (level === 0) {
          // 一级分类默认展开
          expandedKeys.push(node.id);
        }
        // 不再递归展开三级及以下
        if (level < 1 && node.children && node.children.length > 0) {
          collectExpandedKeys(node.children, level + 1);
        }
      });
    };
    collectExpandedKeys(data);
    defaultExpandedKeys.value = expandedKeys;

    // 默认不选中任何组织架构（不传organizationId）
    // 用户需要手动选择二级及以上分类来过滤话术
  } catch (error) {
    console.error('获取组织机构树失败:', error);
  }
};

// 处理树节点点击
const handleTreeNodeClick = (data: Organization) => {
  // 如果是一级分类，清空选中状态（不传organizationId）
  if (data.level === 0) {
    selectedOrganizationId.value = null;
  } else {
    selectedOrganizationId.value = data.id;
  }

  // 根据选中的组织机构过滤话术数据
  if (activeTab.value === 'languageSkill') {
    currentPage.value = 1;
    getList();
  }
  console.log('选中的组织机构:', data);
};

// 处理树节点右键点击
const handleTreeNodeRightClick = (event: MouseEvent, data: Organization, node: any) => {
  // 右键菜单功能可以在这里实现
  console.log('右键点击:', data);
};

// 处理节点操作
const handleNodeAction = (command: string, data: Organization, node: any) => {
  switch (command) {
    case 'add':
      handleAddOrganization(data);
      break;
    case 'edit':
      handleEditOrganization(data);
      break;
    case 'delete':
      handleDeleteOrganization(data);
      break;
  }
};

// 新增组织机构
const handleAddOrganization = (parentData?: Organization) => {
  organizationDialogType.value = 'add';
  Object.assign(organizationForm, {
    id: null,
    departmentName: '',
    parentId: parentData ? parentData.id : null,
    level: parentData ? parentData.level + 1 : 0,
    accountType: userStore.tenantId
  });
  organizationDialogVisible.value = true;
};

// 新增二级分类（从头部按钮触发）
const handleAddSecondLevelOrganization = () => {
  // 找到一级分类（level为0的分类）
  const firstLevelDepartment = organizationTreeData.value.find((dept) => dept.level === 0);
  if (firstLevelDepartment) {
    handleAddOrganization(firstLevelDepartment);
  } else {
    ElMessage.warning('未找到一级分类，无法新增二级分类');
  }
};

// 编辑组织机构
const handleEditOrganization = (data: Organization) => {
  organizationDialogType.value = 'edit';
  Object.assign(organizationForm, {
    id: data.id,
    departmentName: data.departmentName,
    parentId: data.parentId,
    level: data.level,
    accountType: data.accountType
  });
  organizationDialogVisible.value = true;
};

// 删除组织机构
const handleDeleteOrganization = (data: Organization) => {
  ElMessageBox.confirm(`确认删除分类"${data.departmentName}"吗？删除后该分类下的所有话术也将被删除。`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteOrganization(data.id);
      ElMessage.success('删除成功');
      getOrganizationTreeData();
    } catch (error: any) {
      console.error('删除失败:', error);
      const errorMsg = error?.response?.data?.msg || error?.message || '删除失败';
      ElMessage.error(errorMsg);
    }
  });
};

// 提交组织机构表单
const handleOrganizationSubmit = async () => {
  if (!organizationForm.departmentName.trim()) {
    ElMessage.warning('请输入分类名称');
    return;
  }

  try {
    if (organizationDialogType.value === 'add') {
      await addOrganization({
        departmentName: organizationForm.departmentName,
        parentId: organizationForm.parentId,
        level: organizationForm.level,
        accountType: organizationForm.accountType
      });
      ElMessage.success('新增成功');
    } else {
      await updateOrganization({
        id: organizationForm.id!,
        departmentName: organizationForm.departmentName,
        parentId: organizationForm.parentId,
        level: organizationForm.level,
        accountType: organizationForm.accountType
      });
      ElMessage.success('编辑成功');
    }
    organizationDialogVisible.value = false;
    getOrganizationTreeData();
  } catch (error: any) {
    console.error('提交失败:', error);
    const errorMsg = error?.response?.data?.msg || error?.message || '提交失败';
    ElMessage.error(errorMsg);
  }
};

// 获取父级分类名称
const getParentDepartmentName = (parentId: number): string => {
  const findDepartment = (nodes: Organization[]): string => {
    for (const node of nodes) {
      if (node.id === parentId) {
        return node.departmentName;
      }
      if (node.children && node.children.length > 0) {
        const result = findDepartment(node.children);
        if (result) return result;
      }
    }
    return '';
  };
  return findDepartment(organizationTreeData.value);
};

// 获取选中组织架构名称
const getSelectedOrganizationName = (): string => {
  if (!selectedOrganizationId.value) return '';
  const findDepartment = (nodes: Organization[]): string => {
    for (const node of nodes) {
      if (node.id === selectedOrganizationId.value) {
        return node.departmentName;
      }
      if (node.children && node.children.length > 0) {
        const result = findDepartment(node.children);
        if (result) return result;
      }
    }
    return '';
  };
  return findDepartment(organizationTreeData.value);
};

// 获取列表数据
const getList = async () => {
  loading.value = true;
  try {
    const commonParams = { current: currentPage.value, size: pageSize.value };

    if (activeTab.value === 'aiModel') {
      const params: any = { ...commonParams };
      if (filterForm.modelName) {
        params.modelName = filterForm.modelName;
      }
      const { data } = await getModelList(params);
      modelList.value = data.records;
      total.value = data.total;
    } else if (activeTab.value === 'languageSkill') {
      const params: any = { ...commonParams };
      if (filterForm.issue) {
        params.issue = filterForm.issue;
      }
      if (filterForm.answer) {
        params.answer = filterForm.answer;
      }
      if (filterForm.status) {
        params.status = filterForm.status;
      }
      // 添加组织机构ID参数
      if (selectedOrganizationId.value) {
        params.organizationId = selectedOrganizationId.value;
      }
      const { data } = await getAIModelList(params);
      scriptList.value = data.records;
      total.value = data.total;
    } else if (activeTab.value === 'file') {
      const params: any = { ...commonParams };
      if (filterForm.fileName) {
        params.fileName = filterForm.fileName;
      }
      const { data } = await getFileList(params);
      fileList.value = data.records;
      total.value = data.total;
    }
  } catch (error) {
    console.error('获取列表失败:', error);
  } finally {
    loading.value = false;
  }
};

// 查询方法
const handleSearch = () => {
  currentPage.value = 1;
  getList();
};

// 重置方法
const resetFilter = () => {
  filterForm.modelName = '';
  filterForm.issue = '';
  filterForm.answer = '';
  filterForm.fileName = '';
  filterForm.status = '';
  handleSearch();
};

// 分页方法
const handlePagination = ({ pageNum, pageSize: size }: { pageNum: number; pageSize: number }) => {
  currentPage.value = pageNum;
  pageSize.value = size;
  getList();
};

// 筛选条件变化
const handleFilterChange = (val: any) => {
  Object.assign(filterForm, val);
};

// 切换Tab
const handleTabClick = () => {
  currentPage.value = 1;
  total.value = 0;
  modelList.value = [];
  scriptList.value = [];
  fileList.value = [];
  resetFilter();

  // 如果切换到话术训练tab且有选中的组织架构，则加载数据
  if (activeTab.value === 'languageSkill' && selectedOrganizationId.value) {
    setTimeout(() => {
      getList();
    }, 100);
  }
};

// 模型相关方法
const handleAddModel = () => {
  dialogType.value = 'add';
  Object.assign(modelForm, {
    modelName: '',
    aiRoleSetting: '',
    businessBackground: '',
    dialogueCase: ''
  });
  modelDialogVisible.value = true;
};

const handleEditModel = (row: AIModel) => {
  dialogType.value = 'edit';
  Object.assign(modelForm, row);
  modelDialogVisible.value = true;
};

const handleDeleteModel = (row: AIModel) => {
  ElMessageBox.confirm('确认删除该模型吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteAIModel(row.id);
      ElMessage.success('删除成功');
      handleSearch();
    } catch (error: any) {
      console.error('删除失败:', error);
      const errorMsg = error?.response?.data?.msg || error?.message || '删除失败';
      ElMessage.error(errorMsg);
    }
  });
};

const handleModelSubmit = async () => {
  if (!modelFormRef.value) return;

  await modelFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          await addAIModel(modelForm as Omit<AIModel, 'id'>);
          ElMessage.success('新增成功');
        } else {
          await updateAIModel(modelForm as AIModel);
          ElMessage.success('编辑成功');
        }
        modelDialogVisible.value = false;
        getModelOptions();
        handleSearch();
      } catch (error: any) {
        console.error('提交失败:', error);
        const errorMsg = error?.response?.data?.msg || error?.message || '提交失败';
        ElMessage.error(errorMsg);
      }
    }
  });
};

// 模板生成函数
const handleGenerateTemplate = async () => {
  if (!modelForm.modelName) {
    ElMessage.warning('请先输入所属行业');
    return;
  }
  generatingTemplate.value = true;
  templateDisabled.value = true;
  try {
    const { data } = await getAiTemplate({ industry: modelForm.modelName });
    modelForm.aiRoleSetting = data.aiRoleSetting;
    modelForm.businessBackground = data.businessBackground;
    modelForm.dialogueCase = data.dialogueCase;
    ElMessage.success('模板生成成功');
  } catch (error: any) {
    console.error('生成模板失败:', error);
    const errorMsg = error?.response?.data?.msg || error?.message || '生成模板失败';
    ElMessage.error(errorMsg);
  } finally {
    generatingTemplate.value = false;
    templateDisabled.value = false;
  }
};

// 话术相关方法
const handleAddScript = () => {
  resetScriptForm();
  scriptDialogVisible.value = true;
};

const handleEditScript = (row: LanguageSkill) => {
  scriptForm.id = row.id.toString();
  scriptForm.modelId = row.aiModelId.toString();
  scriptForm.question = row.issue;
  scriptForm.answer = row.answer;
  scriptForm.vectorId = row.vectorId || '';
  scriptForm.departmentName = (row as any).departmentName || '';
  scriptDialogVisible.value = true;
};

const handleDeleteScript = (row: LanguageSkill) => {
  ElMessageBox.confirm('确认删除该话术吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteLanguageSkill(row.id);
      ElMessage.success('删除成功');
      getList();
    } catch (error: any) {
      console.error('删除失败:', error);
      const errorMsg = error?.response?.data?.msg || error?.message || '删除失败';
      ElMessage.error(errorMsg);
    }
  });
};

// 话术状态切换
const handleStatusChange = async (row: LanguageSkill) => {
  try {
    await updateLanguageSkillStatus({
      id: row.id,
      accountType: row.accountType,
      aiModelId: row.aiModelId,
      status: row.type,
      type: row.type,
      vectorId: row.vectorId
    });
    ElMessage.success(`话术${row.type === '1' ? '启用' : '禁用'}成功`);
    // 状态切换完成后刷新列表
    getList();
  } catch (error: any) {
    // 如果更新失败，恢复原状态
    row.type = row.type === '1' ? '2' : '1';
    console.error('状态更新失败:', error);
    const errorMsg = error?.response?.data?.msg || error?.message || '状态更新失败';
    ElMessage.error(errorMsg);
  }
};

const handleScriptSubmit = async () => {
  try {
    if (!scriptForm.modelId) {
      ElMessage.warning('请选择所属行业');
      return;
    }
    if (!scriptForm.question.trim()) {
      ElMessage.warning('请输入问题');
      return;
    }
    if (scriptForm.question.length > 2000) {
      ElMessage.warning('问题内容不能超过2000个字符');
      return;
    }
    if (!scriptForm.answer.trim()) {
      ElMessage.warning('请输入回答');
      return;
    }
    if (scriptForm.answer.length > 2000) {
      ElMessage.warning('回答内容不能超过2000个字符');
      return;
    }
    // 允许在没有选中组织架构时添加话术（不传organizationId）
    const data: any = {
      accountType: userStore.tenantId,
      aiModelId: Number(scriptForm.modelId),
      issue: scriptForm.question,
      answer: scriptForm.answer,
      vectorId: scriptForm.vectorId,
      status: '1',
      type: '1',
      createBy: 'admin'
    };

    // 只有选中了组织架构才传递organizationId
    if (selectedOrganizationId.value) {
      data.organizationId = selectedOrganizationId.value;
    }

    if (scriptForm.id) {
      await updateLanguageSkill({
        ...data,
        id: Number(scriptForm.id),
        type: '1',
        updateBy: 'admin'
      });
    } else {
      await addLanguageSkill(data);
    }

    scriptDialogVisible.value = false;
    ElMessage.success(scriptForm.id ? '编辑成功' : '新增成功');
    getList();
  } catch (error: any) {
    console.error(scriptForm.id ? '编辑失败:' : '新增失败:', error);
    const errorMsg = error?.response?.data?.msg || error?.message || (scriptForm.id ? '编辑失败' : '新增失败');
    ElMessage.error(errorMsg);
  }
};

const resetScriptForm = () => {
  scriptForm.id = '';
  scriptForm.modelId = '';
  scriptForm.question = '';
  scriptForm.answer = '';
  scriptForm.vectorId = '';
  scriptForm.departmentName = '';
};

const handleUploadScript = () => {
  importScriptForm.modelId = '';
  importScriptForm.file = null;
  uploadFileList.value = [];
  if (uploadRef.value) {
    uploadRef.value.clearFiles();
  }
  importScriptDialogVisible.value = true;
};

// 文件选择处理
const handleFileChange = (file: any) => {
  // 检查文件大小限制（100MB = 100 * 1024 * 1024 bytes）
  const maxSize = 100 * 1024 * 1024; // 100MB
  if (file.raw && file.raw.size > maxSize) {
    ElMessage.error(`文件大小不能超过100MB，当前文件大小：${(file.raw.size / 1024 / 1024).toFixed(2)}MB`);
    return;
  }

  importScriptForm.file = file.raw;
};

// 导入话术提交
const handleImportScriptSubmit = async () => {
  if (!importScriptForm.modelId) {
    ElMessage.warning('请选择模型');
    return;
  }
  if (!importScriptForm.file) {
    ElMessage.warning('请选择文件');
    return;
  }
  // 允许在没有选中组织架构时导入话术（不传organizationId）

  importScriptLoading.value = true;
  try {
    const formData = new FormData();
    formData.append('file', importScriptForm.file);
    formData.append('aiModelId', importScriptForm.modelId);
    formData.append('accountType', userStore.tenantId);
    formData.append('createBy', 'admin');

    // 只有选中了组织架构才传递organizationId
    if (selectedOrganizationId.value) {
      formData.append('organizationId', selectedOrganizationId.value.toString());
    }
    await uploadLanguageSkills(formData);
    ElMessage.success('导入成功');
    importScriptDialogVisible.value = false;
    getList();
  } catch (error: any) {
    console.error('导入失败:', error);
    // 显示后端返回的具体错误信息
    const errorMsg = error?.response?.data?.msg || error?.message || '导入失败';
    ElMessage.error(errorMsg);
  } finally {
    importScriptLoading.value = false;
  }
};

const handleExportScript = async () => {
  ElMessage.info('导出话术功能正在开发中，敬请期待！');
  return;
  if (exportScriptLoading.value) return;
  exportScriptLoading.value = true;
  try {
    let response = await exportLanguageSkills({
      current: currentPage.value,
      size: pageSize.value,
      accountType: userStore.tenantId,
      status: filterForm.status || undefined,
      issue: filterForm.issue || undefined,
      answer: filterForm.answer || undefined
    });
    if (response.data instanceof Blob && response.data.size > 0) {
      // 正常下载
      const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = '话术训练.xlsx';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    } else {
      ElMessage.error('导出失败，后端未返回文件流');
    }

    // const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    // const link = document.createElement('a');
    // link.href = window.URL.createObjectURL(blob);
    // link.download = '话术训练.xlsx';
    // document.body.appendChild(link);
    // link.click();
    // document.body.removeChild(link);
    // window.URL.revokeObjectURL(link.href);
  } catch (error: any) {
    console.error('导出失败:', error);
    const errorMsg = error?.response?.data?.msg || error?.message || '导出失败';
    ElMessage.error(errorMsg);
  } finally {
    exportScriptLoading.value = false;
  }
};

const handleDownloadTemplate = () => {
  window.open(`${import.meta.env.VITE_GLOB_APP_IMG_URL}juliao/excel/话术训练导入模板.xlsx`, '_blank');
};

// 文件相关方法
const handleUploadFile = async () => {
  if (uploadFileLoading.value) return;
  uploadFileLoading.value = true;
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = '.xlsx,.xls,.doc,.docx,.pdf,.txt';

  // 添加取消选择的处理
  const resetLoading = () => {
    uploadFileLoading.value = false;
  };

  input.onchange = async (e: Event) => {
    const target = e.target as HTMLInputElement;
    if (target.files && target.files[0]) {
      try {
        const file = target.files[0];

        // 检查文件大小限制（100MB = 100 * 1024 * 1024 bytes）
        const maxSize = 100 * 1024 * 1024; // 100MB
        if (file.size > maxSize) {
          ElMessage.error(`文件大小不能超过100MB，当前文件大小：${(file.size / 1024 / 1024).toFixed(2)}MB`);
          resetLoading();
          return;
        }

        const formData = new FormData();
        formData.append('file', file);
        formData.append('createBy', 'admin');
        await uploadFile(formData);
        ElMessage.success('上传成功');
        getList();
      } catch (error: any) {
        const errorMsg = error?.response?.data?.msg || error?.message || '上传失败';
        ElMessage.error(errorMsg);
      } finally {
        resetLoading();
      }
    } else {
      // 用户取消选择文件
      resetLoading();
    }
  };

  // 添加点击取消的处理
  input.oncancel = () => {
    resetLoading();
  };

  input.click();
};

const handleDeleteFile = (row: FileInfo) => {
  ElMessageBox.confirm('确认删除该文件吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteFile(row.id);
      ElMessage.success('删除成功');
      getList();
    } catch (error: any) {
      console.error('删除失败:', error);
      const errorMsg = error?.response?.data?.msg || error?.message || '删除失败';
      ElMessage.error(errorMsg);
    }
  });
};

// 初始化
onMounted(() => {
  getModelOptions();
  getOrganizationTreeData();
  getList();
});
</script>

<style lang="scss" scoped>
.ai-train-container {
  padding: 20px;
  min-height: calc(100vh - 40px);

  .ai-train-tabs {
    margin-top: 20px;
    background-color: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  }

  // 话术训练左右布局
  .language-skill-layout {
    display: flex;
    gap: 20px;
    height: calc(100vh - 200px);
    overflow: hidden;

    // 响应式设计
    @media (max-width: 1200px) {
      flex-direction: column;
      height: auto;
      gap: 16px;
    }

    .organization-tree-section {
      width: 320px;
      min-width: 280px;
      max-width: 400px;
      background: linear-gradient(135deg, #f8fafc 0%, #ffffff 100%);
      border-radius: 12px;
      box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.08);
      border: 1px solid #e2e8f0;
      display: flex;
      flex-direction: column;
      overflow: hidden;
      transition: all 0.3s ease;

      // 响应式设计
      @media (max-width: 1200px) {
        width: 100%;
        max-width: none;
        min-width: auto;
        height: 300px;
      }

      // 悬停效果
      &:hover {
        box-shadow: 0 6px 25px 0 rgba(0, 0, 0, 0.12);
        // transform: translateY(-2px);
      }

      .tree-header {
        padding: 14px 16px;
        background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
        color: white;
        flex-shrink: 0;

        .header-content {
          display: flex;
          justify-content: space-between;
          align-items: center;

          h4 {
            margin: 0;
            font-size: 14px;
            font-weight: 500;
            color: white;
            display: flex;
            align-items: center;

            &::before {
              content: '📋';
              margin-right: 6px;
              font-size: 14px;
            }
          }

          .el-button {
            background: rgba(255, 255, 255, 0.15);
            border: 1px solid rgba(255, 255, 255, 0.25);
            color: white;
            font-size: 12px;
            padding: 6px 12px;
            height: auto;

            &:hover {
              background: rgba(255, 255, 255, 0.25);
              border-color: rgba(255, 255, 255, 0.4);
              // transform: translateY(-1px);
              box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            }

            &:active {
              transform: translateY(0);
            }
          }
        }
      }

      .tree-container {
        flex: 1;
        padding: 12px;
        overflow-x: auto;
        overflow-y: auto;
        background: #f8f9fa;

        // 美化滚动条
        &::-webkit-scrollbar {
          width: 6px;
          height: 6px;
        }

        &::-webkit-scrollbar-track {
          background: rgba(64, 158, 255, 0.1);
          border-radius: 3px;
        }

        &::-webkit-scrollbar-thumb {
          background: rgba(64, 158, 255, 0.3);
          border-radius: 3px;

          &:hover {
            background: rgba(64, 158, 255, 0.5);
          }
        }

        &::-webkit-scrollbar-corner {
          background: rgba(64, 158, 255, 0.1);
        }

        .empty-state {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          height: 200px;
          text-align: center;

          .empty-icon {
            font-size: 48px;
            margin-bottom: 16px;
            opacity: 0.6;
          }

          .empty-text {
            font-size: 16px;
            font-weight: 500;
            color: #64748b;
            margin-bottom: 8px;
          }

          .empty-desc {
            font-size: 14px;
            color: #94a3b8;
          }
        }

        .organization-tree {
          min-width: 292px;
          width: max-content;

          // 一级分类样式
          :deep(.el-tree-node:first-child) {
            &.is-current > .el-tree-node__content {
              background: linear-gradient(135deg, #d4edff 0%, #c7e2ff 100%) !important;
              border-color: #409eff !important;
              // transform: translateX(2px);
              box-shadow: 0 3px 8px rgba(64, 158, 255, 0.2) !important;
            }
            .el-tree-node__content {
              height: 40px;
              padding: 8px 12px;
              // padding-left: 12px !important;
              border-radius: 6px;
              margin-bottom: 4px;
              // background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
              border: 1px solid #337ecc;
              // color: white;
              font-weight: 500;
              font-size: 13px;
              box-shadow: 0 2px 6px rgba(64, 158, 255, 0.2);
              white-space: nowrap;

              &:hover {
                background: linear-gradient(135deg, #d4edff 0%, #c7e2ff 100%);
                border-color: #409eff;
                // transform: translateX(2px);
                box-shadow: 0 3px 8px rgba(64, 158, 255, 0.2);
              }
            }
          }

          // 二级分类样式
          :deep(.el-tree-node__children .el-tree-node:not(.el-tree-node__children .el-tree-node .el-tree-node)) {
            &.is-current > .el-tree-node__content {
              background: linear-gradient(135deg, #d4edff 0%, #c7e2ff 100%) !important;
              border-color: #409eff !important;
              // transform: translateX(2px);
              box-shadow: 0 3px 8px rgba(64, 158, 255, 0.2) !important;
            }
            margin-left: 16px;
            position: relative;

            &::before {
              content: '';
              position: absolute;
              left: -16px;
              top: 0;
              bottom: 0;
              width: 1px;
              background: #409eff;
              opacity: 0.6;
            }

            .el-tree-node__content {
              height: 36px;
              padding: 6px 10px;
              // padding-left: 32px !important;
              border-radius: 4px;
              margin-bottom: 2px;
              background: linear-gradient(135deg, #f0f8ff 0%, #e8f4ff 100%);
              border: 1px solid #c7e2ff;
              color: #2c5aa0;
              font-weight: 400;
              font-size: 12px;
              margin-left: 12px;
              position: relative;
              white-space: nowrap;

              &::before {
                content: '';
                position: absolute;
                left: -12px;
                top: 50%;
                transform: translateY(-50%);
                width: 8px;
                height: 1px;
                background: #409eff;
                opacity: 0.6;
              }

              &:hover {
                background: linear-gradient(135deg, #d4edff 0%, #c7e2ff 100%);
                border-color: #409eff;
                // transform: translateX(2px);
                box-shadow: 0 3px 8px rgba(64, 158, 255, 0.2);
              }
            }
          }

          // 三级分类样式
          :deep(.el-tree-node__children .el-tree-node .el-tree-node) {
            &.is-current > .el-tree-node__content {
              background: linear-gradient(135deg, #d4edff 0%, #c7e2ff 100%) !important;
              border-color: #409eff !important;
              // transform: translateX(2px);
              box-shadow: 0 3px 8px rgba(64, 158, 255, 0.2) !important;
            }
            margin-left: 15px;

            .el-tree-node__content {
              height: 32px;
              padding: 4px 8px;
              // padding-left: 52px !important;
              border-radius: 3px;
              margin-bottom: 1px;
              background: linear-gradient(135deg, #fafbff 0%, #f5f8ff 100%);
              border: 1px solid #dde7ff;
              color: #5a7ba7;
              font-size: 11px;
              font-weight: 400;
              margin-left: 12px;
              position: relative;
              white-space: nowrap;

              &::before {
                content: '';
                position: absolute;
                left: -12px;
                top: 50%;
                transform: translateY(-50%);
                width: 8px;
                height: 1px;
                background: #409eff;
                opacity: 0.4;
              }

              &:hover {
                background: linear-gradient(135deg, #d4edff 0%, #c7e2ff 100%);
                border-color: #409eff;
                // transform: translateX(2px);
                box-shadow: 0 3px 8px rgba(64, 158, 255, 0.2);
              }
            }
          }

          // 通用样式 - 移除默认padding-left
          :deep(.el-tree-node__content) {
            transition: all 0.2s ease;
            padding-left: 0 !important;

            .node-actions {
              opacity: 0;
              transition: opacity 0.2s ease;
            }

            &:hover .node-actions {
              opacity: 1;
            }
          }

          :deep(.el-tree-node__expand-icon) {
            color: #8b9dc3;
            font-size: 14px;

            &:hover {
              color: #409eff;
            }
          }

          .tree-node {
            display: flex;
            align-items: center;
            justify-content: space-between;
            width: 100%;
            min-width: 0;

            .node-label {
              white-space: nowrap;
              flex: 1;
              margin-right: 6px;
              min-width: 0;
            }

            .node-actions {
              opacity: 0;
              transition: all 0.2s ease;
              flex-shrink: 0;

              .action-btn {
                padding: 4px;
                min-height: auto;
                border-radius: 4px;
                background: rgba(255, 255, 255, 0.9);
                border: 1px solid #d1e7ff;

                &:hover {
                  background: #409eff;
                  border-color: #409eff;
                  transform: scale(1.05);

                  .el-icon {
                    color: white;
                  }
                }

                .el-icon {
                  font-size: 12px;
                  color: #8b9dc3;
                  transition: color 0.2s ease;
                }
              }
            }
          }
        }
      }
    }
  }

  .table-section {
    flex: 1;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .operation-section {
      margin-bottom: 16px;
      display: flex;
      gap: 12px;
    }

    .custom-table {
      flex: 1;

      :deep(.el-table__header) {
        th {
          background-color: #f5f7fa;
          color: #606266;
          font-weight: 600;
        }
      }

      :deep(.el-table__row) {
        &:hover {
          td {
            background-color: #f5f7fa;
          }
        }
      }

      .content-text {
        line-height: 1.5;
        word-break: break-all;
        max-height: 60px;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 3;
        line-clamp: 3;
        -webkit-box-orient: vertical;
      }
    }
  }

  .model-dialog {
    :deep(.el-dialog__body) {
      padding: 20px 30px;
    }

    .model-form {
      :deep(.el-form-item__label) {
        font-weight: 500;
      }

      .industry-input {
        display: flex;
        align-items: center;
        gap: 10px;
      }

      .form-label {
        display: flex;
        align-items: center;
        gap: 4px;
        font-weight: 500;
        color: #606266;

        .el-icon {
          color: #909399;
          cursor: pointer;
          font-size: 14px;
          margin-top: 2px;

          &:hover {
            color: #409eff;
          }
        }
      }

      :deep(.el-textarea__inner) {
        font-family: inherit;
        line-height: 1.5;
      }
    }
  }

  .script-dialog {
    :deep(.el-dialog__body) {
      padding: 20px 30px;
    }

    .script-form {
      :deep(.el-form-item__label) {
        font-weight: 500;
      }

      .model-select {
        width: 100%;
      }

      .selected-org {
        color: #409eff;
        font-weight: 500;
      }

      .text-muted {
        color: #909399;
        font-style: italic;
      }
    }
  }

  .import-script-dialog {
    :deep(.el-dialog__body) {
      padding: 20px 30px;
    }

    .import-script-form {
      :deep(.el-form-item__label) {
        font-weight: 500;
      }

      .model-select {
        width: 100%;
      }

      .selected-org {
        color: #409eff;
        font-weight: 500;
      }

      .text-muted {
        color: #909399;
        font-style: italic;
      }
    }
  }

  .organization-dialog {
    :deep(.el-dialog__body) {
      padding: 20px 30px;
    }

    .organization-form {
      :deep(.el-form-item__label) {
        font-weight: 500;
      }

      .text-muted {
        color: #909399;
        font-style: italic;
      }
    }
  }

  // 动画关键帧
  @keyframes slideInFromLeft {
    from {
      opacity: 0;
      transform: translateX(-20px);
    }
    to {
      opacity: 1;
      transform: translateX(0);
    }
  }

  @keyframes fadeIn {
    from {
      opacity: 0;
    }
    to {
      opacity: 1;
    }
  }

  @keyframes pulse {
    0%,
    100% {
      transform: scale(1);
    }
    50% {
      transform: scale(1.05);
    }
  }

  // 导入话术对话框样式
  .import-script-dialog {
    :deep(.el-dialog__header) {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      border-radius: 8px 8px 0 0;
      padding: 16px 20px;

      .el-dialog__title {
        font-size: 17px;
        font-weight: 600;
      }

      .el-dialog__headerbtn {
        .el-dialog__close {
          color: white;
          font-size: 16px;

          &:hover {
            color: #f0f0f0;
          }
        }
      }
    }

    :deep(.el-dialog__body) {
      padding: 0;
    }

    :deep(.el-dialog__footer) {
      background: #f8f9fa;
      border-radius: 0 0 8px 8px;
      padding: 16px 20px;
      border-top: 1px solid #e9ecef;
    }
  }

  .import-container {
    padding: 16px;
    // 表单项样式优化
    :deep(.el-form-item) {
      margin-bottom: 0;
    }

    :deep(.el-form-item__content) {
      line-height: normal;
    }
    .import-steps {
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 20px;
      padding: 16px;
      background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
      border-radius: 8px;

      .step-item {
        display: flex;
        align-items: center;
        flex-direction: column;
        text-align: center;
        min-width: 100px;

        .step-number {
          width: 30px;
          height: 30px;
          border-radius: 50%;
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          color: white;
          display: flex;
          align-items: center;
          justify-content: center;
          font-weight: 600;
          font-size: 14px;
          margin-bottom: 6px;
          box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
        }

        .step-content {
          h4 {
            margin: 0 0 2px 0;
            font-size: 13px;
            font-weight: 600;
            color: #303133;
          }

          p {
            margin: 0;
            font-size: 11px;
            color: #909399;
          }
        }
      }

      .step-arrow {
        font-size: 16px;
        color: #667eea;
        margin: 0 12px;
        font-weight: bold;
      }
    }

    .config-section,
    .template-section,
    .upload-section {
      margin-bottom: 16px;

      .section-header {
        display: flex;
        align-items: center;
        margin-bottom: 10px;
        font-size: 15px;
        font-weight: 600;
        color: #303133;

        .header-icon {
          margin-right: 6px;
          font-size: 16px;
          color: #667eea;
        }
      }
    }

    .config-card {
      padding: 16px;
      background: white;
      border: 1px solid #e4e7ed;
      border-radius: 8px;
      margin-bottom: 12px;

      .config-form {
        .category-display {
          display: flex;
          align-items: center;
          padding: 6px 10px;
          background: #f5f7fa;
          border-radius: 4px;
          border: 1px solid #e4e7ed;

          .category-icon {
            margin-right: 6px;
            color: #409eff;
          }

          .selected-org {
            color: #303133;
            font-weight: 500;
          }

          .text-muted {
            color: #909399;
          }
        }

        .model-select {
          width: 100%;
        }
      }
    }

    .template-card {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 16px;
      background: white;
      border: 1px solid #e4e7ed;
      border-radius: 8px;
      transition: all 0.3s ease;

      &:hover {
        border-color: #667eea;
        box-shadow: 0 2px 12px rgba(102, 126, 234, 0.1);
      }

      .template-info {
        display: flex;
        align-items: center;

        .file-icon {
          font-size: 28px;
          color: #67c23a;
          margin-right: 12px;
        }

        .file-details {
          h5 {
            margin: 0 0 2px 0;
            font-size: 15px;
            font-weight: 600;
            color: #303133;
          }

          p {
            margin: 0;
            font-size: 13px;
            color: #909399;
          }
        }
      }

      .download-btn {
        padding: 10px 20px;
        border-radius: 6px;
        font-weight: 500;
        box-shadow: 0 2px 6px rgba(64, 158, 255, 0.3);

        &:hover {
          transform: translateY(-1px);
          box-shadow: 0 3px 12px rgba(64, 158, 255, 0.4);
        }
      }
    }

    .upload-area {
      :deep(.el-upload-dragger) {
        border: 2px dashed #d9d9d9;
        border-radius: 8px;
        background: #fafbfc;
        transition: all 0.3s ease;
        padding: 30px 16px;

        &:hover {
          border-color: #667eea;
          background: #f0f2ff;
        }

        .upload-content {
          display: flex;
          flex-direction: column;
          align-items: center;

          .upload-icon {
            font-size: 40px;
            color: #c0c4cc;
            margin-bottom: 12px;
          }

          .upload-text {
            .main-text {
              margin: 0 0 6px 0;
              font-size: 15px;
              color: #606266;
              font-weight: 500;
            }

            .sub-text {
              margin: 0;
              font-size: 13px;
              color: #909399;
            }
          }
        }
      }
    }
  }
}
</style>
